/**
 * 
 */
package mm.front.jsf.mb;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import mm.back.entity.Usuario;
import mm.back.entity.enums.Rol;
import mm.back.service.UsuariosService;
import mm.exceptions.MMGenericException;

/**
 * @author PUSDERKIS
 *
 */
public class SessionManagedBean implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1347226823002591680L;
	
	private Usuario userLogged;
	
	private boolean logOk=false;

	/**
	 * @return the logOk
	 */
	public boolean isLogOk() {
		return logOk;
	}

	private transient UsuariosService usuariosService;
	
	

	public String logIn(){
		
		Usuario u = null;
		try {
			u = usuariosService.login(userLogged.getUserName(), userLogged.getPass());
		} catch (MMGenericException e) {
			logOk=false;
		}
		
		
		if (u == null){
			FacesMessage fm = new FacesMessage("Usuario y/o contraseña invalidos.");
			FacesContext.getCurrentInstance().addMessage(null, fm);
			logOk=false;
		} else {
			logOk = true;
			userLogged = u;
		}
		
		return null;
	}
	
	public String logOut(){
		logOk=false;
		FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
		return null;
	}
	
	/**
	 * @return the userLogged
	 */
	public Usuario getUserLogged() {
		return userLogged;
	}

	/**
	 * @param userLogged the userLogged to set
	 */
	public void setUserLogged(Usuario userLogged) {
		this.userLogged = userLogged;
	} 
	
	/**
	 * @param usuariosService the usuariosService to set
	 */
	public void setUsuariosService(UsuariosService usuariosService) {
		this.usuariosService = usuariosService;
	}
	
	public boolean isDuenio(){
		if (userLogged == null) {
			return false;
		}
		
		return Rol.DUENIO.equals(getUserLogged().getRol());
	}


}
